const city = require('../../../utils/city.js');
const cityObjs = require('../../../utils/city.js');
const config = require('../../../utils/config.js');
import locationBehavior from '../../../behaviors/location';
import * as transferData from './../../../models/transferData'

Page({
  behaviors: [locationBehavior],
  data: {
    _query: {},
    _navHeight: 0,
    _topHeight: 0,
    searchLetter: [],
    showLetter: "",
    winHeight: 0,
    cityList: [],
    isShowLetter: false,
    scrollTop: 0, //置顶高度
    scrollTopId: '', //置顶id
    city: "定位中",
    cityCode: '',
    hiddenName: false,
    hotcityList: [ {
      cityCode: 310000,
      city: '上海市'
    }, {
      cityCode: 320500,
      city: '苏州市'
    },
    
      {
        cityCode: 330100,
        city: '杭州市'
      }, {
        cityCode: 320100,
        city: '南京市'
      },
      {
        cityCode: 110000,
        city: '北京市'
      },
      {
        cityCode: 120000,
        city: '天津市'
      }, 
      {
      cityCode: 420100,
      city: '武汉市'
    }, {
        cityCode: 441900,
      city: '东莞市'
      }, {
        cityCode: 360100,
      city: '南昌市'
    }, ],
    commonCityList: [{
      cityCode: 110000,
      city: '北京市'
    }, {
      cityCode: 310000,
      city: '上海市'
    }
    ],

    inputName: '',
    completeList: [],
    condition: false,
  },

  onLoad: function(options) {
    // 生命周期函数--监听页面加载
    this._query = wx.createSelectorQuery();
    const searchLetter = city.searchLetter;
    const cityList = city.cityList();
    const sysInfo = wx.getSystemInfoSync();
    const winHeight = sysInfo.windowHeight;
    const itemH = winHeight / searchLetter.length;
    let tempArr = [];
    this.myData = {
      isLocal: options.local === '1',
      name: options.name || ''
    }
    searchLetter.map(
      (item, index) => {
        let temp = {};
        temp.name = item;
        temp.tHeight = index * itemH;
        temp.bHeight = (index + 1) * itemH;
        tempArr.push(temp)
      }
    );
    this.setData({
      winHeight: winHeight,
      itemH: itemH,
      searchLetter: tempArr,
      cityList: cityList
    }, () => {
      this.getNavNodeHeight()
    });
    var currentCity = wx.getStorageSync('currentCity');
    if (currentCity.city){
      this.setData({
        city: currentCity.city,
        cityCode: currentCity.cityCode,
      })
    }else{
      this.getLocation();
    }
  },

  // 选择右侧字母导航
  clickLetter: function(e) {
    const showLetter = e.currentTarget.dataset.letter;
    this.setData({
      toastShowLetter: showLetter,
      isShowLetter: true,
      scrollTopId: showLetter,
    })
    const that = this;
    setTimeout(function() {
      that.setData({
        isShowLetter: false
      })
    }, 500)
  },

  // 滑动选择结束
  onMoveNav(e) {
    let touchEnd = e.changedTouches[0].pageY - this.data._topHeight
    let lindex = parseInt(touchEnd / this.data._navHeight * this.data.searchLetter.length);
    if (lindex < 0) {
      lindex = 0
    }
    if (lindex >= this.data.searchLetter.length) {
      lindex = this.data.searchLetter.length - 1
    }
    let value = this.data.searchLetter[lindex].name;
    this.clickLetter({
      currentTarget: {
        dataset: {
          letter: value || '',
        }
      }
    })
  },

  // 获取导航高度
  getNavNodeHeight() {
    this._query.select('.nav-box').boundingClientRect()
    this._query.exec((res) => {
      this.data._navHeight = res[0].height;
      this.data._topHeight = res[0].top;
    })
  },

  //选择城市
  bindCity: function(e) {
    this.setData({
      condition: true,
      city: e.currentTarget.dataset.city,
      cityCode: e.currentTarget.dataset.code,
      scrollTop: 0,
      completeList: [],
    })
    var currentCity = {};
    currentCity.city = e.currentTarget.dataset.city;
    currentCity.cityCode = e.currentTarget.dataset.code;

    if(!this.myData.isLocal) {
      wx.setStorageSync("currentCity", currentCity);
      this.setCityTemporary(currentCity)
      
      // 定位
      if (currentCity) {
        this.setWxCityBe(currentCity.city)
      }
      //改变上一页面数据
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];  //上一个页面
      wx.setStorageSync('isChoseCity', true)
      prevPage.setData({
        isChoseCity: true,
        currentCity:currentCity
      })
    }
    if(this.myData.name) {
      transferData.setTemporaryData(this.myData.name, {
        name: currentCity.city,
        code: currentCity.cityCode
      })
    } else {
      transferData.setData('currentCity', {
        name: currentCity.city,
        code: currentCity.cityCode
      })
    }
    wx.navigateBack({
      delta:0
    })
  },

  //点击热门城市回到顶部
  hotCity: function() {
    this.setData({
      scrollTop: 0,
    })
  },
  getLocation: function() {
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: function(res) {
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${config.key}`,
          success: res => {
            that.setData({
              city: res.data.result.ad_info.city,
              cityCode: res.data.result.ad_info.adcode,
            })
          }
        })
      }
    })
  },
  bindBlur: function(e) {
    this.setData({
      inputName: e.detail.value
    })
  },
  bindKeyInput: function(e) {
    if (e.detail.value == '' || e.detail.value == ' ' || e.detail.value.length == 0) {
      this.setData({
        inputName: '',
        hiddenName: false,
        completeList: []
      })
    } else {
      this.setData({
        inputName: e.detail.value,
        hiddenName: true
      })
      this.auto();
    }
  },
  auto: function() {
    let inputSd = this.data.inputName.trim()
    let sd = inputSd.toLowerCase()
    let num = sd.length
    const cityList = cityObjs.cityObjs
    let finalCityList = []

    let temp = cityList.filter(
      item => {
        let text = item.short.slice(0, num).toLowerCase()
        return (text && text == sd)
      }
    )
    //在城市数据中，添加简拼到“shorter”属性，就可以实现简拼搜索
    let tempShorter = cityList.filter(
      itemShorter => {
        if (itemShorter.shorter) {
          let textShorter = itemShorter.shorter.slice(0, num).toLowerCase()
          return (textShorter && textShorter == sd)
        }
        return
      }
    )

    let tempChinese = cityList.filter(
      itemChinese => {
        let textChinese = itemChinese.city.slice(0, num)
        return (textChinese && textChinese == sd)
      }
    )

    if (temp[0]) {
      temp.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        }
      )
      this.setData({
        completeList: finalCityList,
      })
    } else if (tempShorter[0]) {
      tempShorter.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        }
      );
      this.setData({
        completeList: finalCityList,
      })
    } else if (tempChinese[0]) {
      tempChinese.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        })
      this.setData({
        completeList: finalCityList,
      })
    } else {
      return
    }
  },

  reGetLocation() {
    wx.navigateBack()
  }



})
